package com.hscm.boss.common.utils.mails;


import com.hscm.boss.common.utils.mails.model.AttachFile;
import com.hscm.boss.common.utils.mails.model.MailProperties;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

//邮件的客户端
@Component
public class MailClient {

    @Resource // JavaMailSender 对象通过@Component才能注入到容器中
    private JavaMailSender mailSender;

    //简单邮件
    public boolean sendSimple(MailProperties prop) {
        try {
            //创建简单的邮件类
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            //发送邮件者
            simpleMailMessage.setFrom(prop.getFrom());
            //收邮件者
            simpleMailMessage.setTo(prop.getTo());
            //发送时间
            simpleMailMessage.setSentDate(new Date());
            //邮件的主题 正文
            simpleMailMessage.setSubject(prop.getSubject());
            simpleMailMessage.setText(prop.getText());

            //发送邮件 发送失败就会抛异常
            mailSender.send(simpleMailMessage);
            //没有异常返回true
            return true;
        } catch (MailException e) {
            e.printStackTrace();//
        }
        return false;
    }

    //附件邮件
    public boolean sendAttachMail(MailProperties prop) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();

            //辅助发邮件  true表示支付附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //发送邮件者
            helper.setFrom(prop.getFrom());
            //收邮件者
            helper.setTo(prop.getTo());
            //发送时间
            helper.setSentDate(new Date());
            //邮件的主题
            helper.setSubject(prop.getSubject());
            helper.setText(prop.getText());

            List<AttachFile> attachFileList = prop.getAttachFileList();
            //附件不为空 并且附件中有值
            if(attachFileList != null && attachFileList.size() > 0){
                for (AttachFile attachFile : attachFileList) {
                    //添加附件   计划书附件表示收件者看大的附件名字 //附件可以有多个 就是多来几个addAttachment
                    helper.addAttachment(attachFile.getName(), attachFile.getFile());
                }
            }
            //发邮件
            mailSender.send(helper.getMimeMessage());
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }

}
